package gate

import (
	//"github.com/gomqtt/tools"
	//"github.com/liu-junyong/go-logger/logger"
	//. "github.com/256dpi/gomqtt/spec"
	 //"github.com/256dpi/gomqtt/client"
	 "github.com/256dpi/gomqtt/packet"
	 //"github.com/256dpi/gomqtt/broker"

	. "github.com/256dpi/gomqtt/session"
)

var g_playerManager *PlayerManager
var g_tcpManager	*TcpManager

//
//type MyBackend struct {
//	Credentials map[string]string
//
//	subscribedClients    *tools.Tree
//	retainedMessages     *tools.Tree
//	storedSessions       sync.Map
//	activeClients        sync.Map
//	offlineQueues        sync.Map
//	offlineSubscriptions *tools.Tree
//	mutex                sync.Mutex
//}
//
func (this *MyBackend)Init(playerManager *PlayerManager){
	//this.Sessions = make(map[string]*MySession,0)
	//this.clients = make(  map[string]*broker.Client )
	//this.queue = tools.NewTree()
	//this.retained = tools.NewTree()
	//this.offlineQueue = tools.NewTree()
	g_playerManager = playerManager
	g_playerManager.Back = this
}



// Direction denotes a packets direction.
//type Direction hello
//
//const (
//	// Incoming packets are being received.
//	Incoming Direction = iota
//
//	// Outgoing packets are being be sent.
//	Outgoing
//)

// A MySession stores packets in memory.
type MySession struct {
	Counter  *IDCounter
	Incoming *PacketStore
	Outgoing *PacketStore
}

// NewMySession returns a new MySession.
func NewMySession() *MySession {
	return &MySession{
		Counter:  NewIDCounter(),
		Incoming: NewPacketStore(),
		Outgoing: NewPacketStore(),
	}
}

// NextID will return the next id for outgoing packets.
func (s *MySession) NextID() packet.ID {
	return s.Counter.NextID()
}

// SavePacket will store a packet in the session. An eventual existing
// packet with the same id gets quietly overwritten.
func (s *MySession) SavePacket(dir Direction, pkt packet.Generic) error {
	s.storeForDirection(dir).Save(pkt)
	return nil
}

// LookupPacket will retrieve a packet from the session using a packet id.
func (s *MySession) LookupPacket(dir Direction, id packet.ID) (packet.Generic, error) {
	return s.storeForDirection(dir).Lookup(id), nil
}

// DeletePacket will remove a packet from the session. The method must not
// return an error if no packet with the specified id does exists.
func (s *MySession) DeletePacket(dir Direction, id packet.ID) error {
	s.storeForDirection(dir).Delete(id)
	return nil
}

// AllPackets will return all packets currently saved in the session.
func (s *MySession) AllPackets(dir Direction) ([]packet.Generic, error) {
	return s.storeForDirection(dir).All(), nil
}

// Reset will completely reset the session.
func (s *MySession) Reset() error {
	// reset counter and stores
	s.Counter.Reset()
	s.Incoming.Reset()
	s.Outgoing.Reset()

	return nil
}

func (s *MySession) storeForDirection(dir Direction) *PacketStore {
	if dir == Incoming {
		return s.Incoming
	} else if dir == Outgoing {
		return s.Outgoing
	}

	panic("unknown direction")
}
